<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索添加 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
          <el-button type="danger" @click="delGroup" :disabled="this.sels.length === 0">批量删除</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe @selection-change="selsChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <!-- <el-table-column type="index"></el-table-column> -->

        <el-table-column label="账号" prop="username"></el-table-column>
        <el-table-column label="昵称" prop="name"></el-table-column>
        <el-table-column label="电话" prop="phone"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status==0?true:false"
              @change="userStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEdit(scope.row.id)"
            ></el-button>

            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="remove(scope.row.id)"
              size="mini"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1,2,5,10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 内容主体 -->
      <el-form :model="user" :rules="rules" ref="user" label-width="70px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="user.username" @input="update($event)"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            placeholder="请输入密码"
            v-model="user.password"
            show-password
            @input="update($event)"
          ></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="user.name" @input="update($event)"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="user.phone" @input="update($event)"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="user.email" @input="update($event)"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="images">
          <el-input v-model="user.imageUrl" v-if="false" @input="update($event)"></el-input>
          <el-upload
            class="avatar-uploader"
            action="http://shop.cn/api/v1.Qny/upload/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" style="border: 1px dashed #d9d9d9;"></i>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('user')">立即创建</el-button>
          <el-button @click="addDialogVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer"></span>
    </el-dialog>

    <!-- 修改用户 -->

    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 内容主体 -->
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="70px">
        <el-form-item label="账号">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input placeholder="请输入密码" v-model="editForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="images">
          <el-input v-model="editForm.imageUrl" v-if="false"></el-input>

          <el-upload
            class="avatar-uploader"
            action="http://shop.cn/api/v1.Qny/upload/"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <!-- 有原数据就用元数据，没有就更换 -->
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <img v-else :src="editForm.imageUrl" class="avatar" />

            <!-- <i v-else class="el-icon-plus avatar-uploader-icon" style="border: 1px dashed #d9d9d9;"></i> -->
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="editUserInfo">编辑</el-button>
          <el-button @click="editDialogVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer"></span>
    </el-dialog>
  </div>
</template>
<script>
import { server } from '../api/index'
export default {
  data() {
    return {
      sels: [], //选中的值显示
      //获取用户列表参数对象
      queryInfo: {
        query: '',
        //当前页数
        pagenum: 1,
        //当前页显示多少条

        pagesize: 10
      },
      user: {},
      imageUrl: '',
      userlist: [],
      total: 0,
      //添加用户对话框
      addDialogVisible: false,
      //修改用户对话框
      editDialogVisible: false,
      //查询到的用户信息对象
      editForm: {},
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          {
            min: 3,
            max: 11,
            message: '长度在 3 到 11 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 32,
            message: '长度在 6 到 32 个字符',
            trigger: 'blur'
          }
        ],
        name: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { min: 11, message: '手机号格式不正确', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    remove(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.delete(id)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    async getUserList() {
      const { data: res } = await server.getAdminList(this.queryInfo)

      if (res.code !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userlist = res.data.data
      this.total = res.data.total
    },
    update: function(e) {
      this.$forceUpdate() // 刷新
    },
    //监听分页改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    //监听页码值
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    //监听switch开关的状态
    async userStatusChange(userinfo) {
      const { data: res } = await server.statusAdmin(
        userinfo.id,
        userinfo.status
      )

      if (res.code !== 200) {
        userinfo.status = !userinfo.status
        return this.$message.error('更新用户状态失败')
      }
      userinfo.status = !userinfo.status

      this.$message.success('更新用户状态成功')
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.imageUrl = res.data
      this.user.imageUrl = res.data
      //完成后清除所有的图片
      this.editForm.imageUrl == URL.createObjectURL(file.raw)
      this.editForm.imageUrl = res.data
      // console.log(res)
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type == 'image/jpeg' ||
        file.type == 'image/png' ||
        file.type == 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const { data: res } = await server.addAdmin(this.user)

          // this.$http.post('/v1.Admin/add', this.user).then(res => {
          if (res.code == 200) {
            this.$message.success('添加成功')
          } else {
            this.$message.error('添加失败')
          }
          this.addDialogVisible = false
          //重新加载数据

          this.imageUrl = ''
          this.user.imageUrl = ''

          this.editForm.imageUrl = ''
          this.getUserList()
        } else {
          alert('请按照规则填写')
          return false
        }
      })
    },

    //关闭事件
    addDialogClosed() {
      this.imageUrl = ''
      this.user.imageUrl = ''
      this.editForm.imageUrl = ''
      this.$refs.user.resetFields()
    },
    //展示用户编辑
    async showEdit(id) {
      const { data: res } = await server.detailAdmin(id)

      if (res.code !== 200) {
        return this.$message.error('查询用户信息失败！')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    //用户修改对话框关闭
    editDialogClosed() {
      this.imageUrl = ''
      this.user.imageUrl = ''
      this.editForm.imageUrl == ''
      this.$refs.editFormRef.resetFields()
    },
    //发起修改用户请求
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await server.editAdmin(
          this.editForm.id,
          this.editForm
        )

        if (res.code != 200) {
          return this.$message.error('编辑用户信息失败！')
        }
        //关闭对话框
        this.editDialogVisible = false
        //刷新列表
        this.imageUrl = ''
        this.user.imageUrl = ''
        this.editForm.imageUrl == ''

        this.getUserList()
        //提示修改成功
        this.$message.success('编辑用户信息成功！')
      })
    },
    //用户删除
    async delete(id) {
      const { data: res } = await server.delAdmin(id)

      if (res.code !== 200) {
        return this.$message.error('删除用户信息失败！')
      }
      //刷新列表
      this.getUserList()
      this.$message.success('删除用户信息成功！')
    },
    selsChange(sels) {
      this.sels = sels
    },
    delGroup() {
      var ids = this.sels.map(item => item.id).join() //获取所有选中行的id组成的字符串，以逗号分隔

      this.$confirm('此操作将永久删除选中文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.delAll(ids)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    async delAll(ids) {
      const { data: res } = await server.delallAdmin(ids)

      if (res.code !== 200) {
        return this.$message.error('删除用户信息失败！')
      }
      //刷新列表
      this.getUserList()
      this.$message.success('删除用户信息成功！')
    }
  }
}
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>